/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-08-15
 * Time: 12:20
 */
class Solution8 {
    // 先计算翻转对利用单调性双指针，再合并数组
    int[] tmp;
    public int reversePairs(int[] nums) {
        int n = nums.length;
        tmp = new int[n];
        return mergeSort(nums,0,n-1);

    }

    public int mergeSort(int[] nums,int left, int right) {
        if(left >= right) {
            return 0;
        }
        int ret = 0;
        int mid =(left+right)/2;
        ret += mergeSort(nums,left,mid);
        ret += mergeSort(nums,mid+1,right);

// 处理一左一右，先计算
        int cur1 = left,cur2 = mid+1,i = left;

        // 升序
        while(cur2 <= right) {
            while(cur1 <= mid && nums[cur2] >= nums[cur1] / 2.0) {
                cur1++;
            }
            if(cur1 > mid) {
                break;
            }
            ret += mid-cur1+1;
            cur2++;
        }

        cur1 = left;cur2 = mid+1;
        while(cur1 <= mid && cur2 <= right) {
            if(nums[cur1] <= nums[cur2]) {
                tmp[i++] = nums[cur1++];
            }else {
                tmp[i++] = nums[cur2++];
            }
        }

        while(cur1 <= mid) {
            tmp[i++] = nums[cur1++];
        }

        while(cur2 <= right) {
            tmp[i++] = nums[cur2++];
        }

        for(int j = left; j <= right; j++) {
            nums[j] = tmp[j];
        }
        return ret;
    }
}
